# import datetime
import hashlib
import io
# import os
import random
# import uuid
from concurrent.futures.thread import ThreadPoolExecutor

# import boto3
import qiniu
import qrcode
import requests
import ujson

from zhipin import app


def _force_bytes(data):
    if type(data) != bytes:
        if type(data) == str:
            data = data.encode()
        elif type(data) == io.BytesIO:
            data = data.getvalue()
        else:
            data = bytes(data)
    return data


def make_sha256_digest(data):
    """生成SHA256摘要"""
    data = _force_bytes(data)
    return hashlib.sha256(data).hexdigest()


def make_md5_digest(data):
    """生成MD5摘要"""
    data = _force_bytes(data)
    return hashlib.md5(data).hexdigest()


def gen_mobile_code(length=6):
    """生成指定长度的手机验证码"""
    return ''.join(random.choices('0123456789', k=length))


@app.task
def send_sms_by_luosimao(tel, message):
    """发送短信（调用螺丝帽短信网关）"""
    resp = requests.post(
        url='http://sms-api.luosimao.com/v1/send.json',
        auth=('api', 'key-ed7e568b0539ca1929f48ca615a27e85'),
        data={'mobile': tel, 'message': message},
        timeout=10,
        verify=False
    )

    return ujson.loads(resp.content)


def gen_qrcode(data):
    """生成二维码"""
    qrcode_image = qrcode.make(data)
    buffer = io.BytesIO()
    qrcode_image.save(buffer)
    return buffer.getvalue()


def get_ip_address(request):
    """获得请求的IP地址"""
    ip = request.META.get('HTTP_X_FORWARDED_FOR', None)
    return ip or request.META['REMOTE_ADDR']


QINIU_ACCESS_KEY = 'KarvlHfUdoG1mZNSfDVS5Vh3nae2jUZumTBHK-PR'
QINIU_SECRET_KEY = 'SFPFkAn5NENhdCMqMe9wd_lxGHAeFR5caXxPTtt7'
QINIU_BUCKET_NAME = 'myzhipin'

AUTH = qiniu.Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)


def upload_file_to_qiniu(file_path, filename):
    """将文件上传到七牛云存储"""
    token = AUTH.upload_token(QINIU_BUCKET_NAME, filename)
    result, *_ = qiniu.put_file(token, filename, file_path)
    return result


def upload_stream_to_qiniu(file_stream, filename, size):
    """将数据流上传到七牛云存储"""
    token = AUTH.upload_token(QINIU_BUCKET_NAME, filename)
    result, *_ = qiniu.put_stream(token, filename, file_stream, None, size)
    return result


# MAX_READ_SIZE = 64 * 1024
#
# AWS3_REGION = 'region_name'
# AWS3_AK = 'access_key'
# AWS3_SK = 'secret_key'
# AWS3_BUCKET = 'bucket_name'
#
# S3 = boto3.client('s3', region_name=AWS3_REGION,
#                   aws_access_key_id=AWS3_AK, aws_secret_access_key=AWS3_SK)
#
#
# def url_from_key(file_key):
#     """通过文件的key拼接访问URL"""
#     return f'https://s3.{AWS3_REGION}.amazonaws.com.cn/{AWS3_BUCKET}/{file_key}'
#
#
# def s3_upload_file(file):
#     """上传文件到亚马逊S3"""
#     hasher = hashlib.md5()
#     file_name, file_size = file.name, file.size
#     key = uuid.uuid4() + "." + os.path.splitext(file_name)[1]
#     multipart_upload_init_info = S3.create_multipart_upload(
#         ACL='public-read', Bucket=AWS3_BUCKET, Key=key,
#         Expires=(datetime.datetime.today() + datetime.timedelta(days=1)),
#     )
#     upload_id = multipart_upload_init_info['UploadId']
#     part_key = multipart_upload_init_info['Key']
#
#     uploaded_size, chunks_number, parts_list = 0, 1, []
#     while uploaded_size <= file_size:
#         chunks = file.read(MAX_READ_SIZE)
#         hasher.update(chunks)
#         chunks_response = S3.upload_part(
#             Body=chunks, Bucket=AWS3_BUCKET, Key=part_key,
#             PartNumber=chunks_number, UploadId=upload_id
#         )
#         parts_list.append({
#             'ETag': chunks_response['ETag'],
#             'PartNumber': chunks_number
#         })
#         chunks_number = chunks_number + 1
#         uploaded_size += MAX_READ_SIZE
#     S3.complete_multipart_upload(
#         Bucket=AWS3_BUCKET, Key=part_key,
#         UploadId=upload_id, MultipartUpload={'Parts': parts_list}
#     )
#     body_md5 = hasher.hexdigest()
#     return url_from_key(key), body_md5


POOL = ThreadPoolExecutor(max_workers=32)


@app.task
def display_info(message):
    print(message)
